import tkinter as tk
from tkinter import ttk
from pathlib import Path
import os

from ui.constants import CHEST_SIZES, SLOT_SIZE, ITEM_SIZE
from ui.widgets import SlotWidget, PageFrame
from core.resource_manager import ResourceManager
from core.animation_engine import AnimationEngine

try:
    from core.markdown_renderer import MarkdownRenderer
    MARKDOWN_SUPPORT = True
except ImportError as e:
    MARKDOWN_SUPPORT = False
    print(f"Markdown支持已禁用: {e}")

class MCUIRenderer:
    def __init__(self, parent_frame, resource_manager: ResourceManager, animation_engine: AnimationEngine):
        self.parent = parent_frame
        self.resource_manager = resource_manager
        self.animation_engine = animation_engine
        self.current_widgets = []
        
        if MARKDOWN_SUPPORT:
            self.markdown_renderer = MarkdownRenderer()
        
    def render_page(self, page_data, mcui_data):
        """渲染页面"""
        # 清除当前内容
        self.clear_page()
        
        page_type = page_data.get('type', 'text')
        
        # 调试信息
        print(f"渲染页面类型: {page_type}")
        
        if page_type == 'text':
            self._render_text_page(page_data, mcui_data)
        elif page_type == 'chest_ui':
            self._render_chest_page(page_data, mcui_data)
        elif page_type == 'custom_grid':
            self._render_custom_grid(page_data, mcui_data)  # 修复：确保方法名正确
        elif page_type == 'md' and MARKDOWN_SUPPORT:
            self._render_markdown_page(page_data, mcui_data)
        elif page_type == 'md' and not MARKDOWN_SUPPORT:
            self._render_markdown_error_page(page_data)
        else:
            self._render_unknown_page(page_data, mcui_data)
    
    def clear_page(self):
        """清除当前页面"""
        # 停止所有动画
        for widget_id in list(self.animation_engine.animated_widgets.keys()):
            self.animation_engine.unregister_animated_item(widget_id)
            
        # 清理Markdown渲染器资源
        if hasattr(self, 'markdown_renderer'):
            self.markdown_renderer.cleanup()
            
        # 移除所有部件
        for widget in self.current_widgets:
            try:
                widget.destroy()
            except:
                pass
        self.current_widgets.clear()
    
    def _render_text_page(self, page_data, mcui_data):
        """渲染文本页面"""
        page_frame = PageFrame(self.parent, page_data)
        page_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        self.current_widgets.append(page_frame)
    
    def _render_chest_page(self, page_data, mcui_data):
        """渲染箱子界面"""
        title = page_data.get('title', '箱子')
        layout = page_data.get('layout', 'minecraft:chest')
        slots = page_data.get('slots', {})
        custom_size = page_data.get('custom_size')
        
        # 创建页面框架
        page_frame = ttk.Frame(self.parent)
        page_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        self.current_widgets.append(page_frame)
        
        # 标题
        title_label = ttk.Label(
            page_frame, 
            text=title,
            font=('Arial', 16, 'bold')
        )
        title_label.pack(pady=10)
        
        # 计算布局
        if custom_size:
            rows, cols = custom_size
        else:
            rows, cols = CHEST_SIZES.get(layout, (3, 9))
        
        # 创建箱子容器
        chest_container = ttk.Frame(page_frame)
        chest_container.pack(expand=True)
        
        # 创建槽位网格
        self._create_slot_grid(chest_container, rows, cols, slots, f"chest_{id(page_data)}")
    
    def _render_custom_grid(self, page_data, mcui_data):
        """渲染自定义网格布局"""
        title = page_data.get('title', '自定义布局')
        rows = page_data.get('rows', 3)
        cols = page_data.get('cols', 9)
        slots = page_data.get('slots', {})
        
        # 创建页面框架
        page_frame = ttk.Frame(self.parent)
        page_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        self.current_widgets.append(page_frame)
        
        # 标题
        if title:
            title_label = ttk.Label(
                page_frame, 
                text=title,
                font=('Arial', 16, 'bold')
            )
            title_label.pack(pady=10)
        
        # 创建网格容器
        grid_container = ttk.Frame(page_frame)
        grid_container.pack(expand=True)
        
        # 创建槽位网格
        self._create_slot_grid(grid_container, rows, cols, slots, f"grid_{id(page_data)}")
    
    def _create_slot_grid(self, parent, rows, cols, slots, namespace):
        """创建槽位网格"""
        for row in range(rows):
            row_frame = ttk.Frame(parent)
            row_frame.pack()
            self.current_widgets.append(row_frame)
            
            for col in range(cols):
                slot_index = row * cols + col
                slot_data = slots.get(str(slot_index), {})
                
                slot_widget = SlotWidget(
                    row_frame, 
                    slot_data,
                    self.resource_manager,
                    self.animation_engine,
                    f"{namespace}_slot_{slot_index}"
                )
                slot_widget.pack(side=tk.LEFT, padx=2, pady=2)
                self.current_widgets.append(slot_widget)
    
    def _render_markdown_page(self, page_data, mcui_data):
        """渲染Markdown页面"""
        file_name = page_data.get('file', '')
        if not file_name:
            self._render_error("Markdown页面未指定文件")
            return
        
        # 获取资源根目录
        assets_root = mcui_data.get('_assets_root', '')
        if not assets_root:
            self._render_error("无法找到资源根目录")
            return
        
        # 构建Markdown文件路径
        md_file_path = Path(assets_root) / "md" / file_name
        
        if not md_file_path.exists():
            self._render_error(f"Markdown文件不存在: {md_file_path}")
            return
        
        # 读取Markdown内容
        try:
            with open(md_file_path, 'r', encoding='utf-8') as f:
                markdown_content = f.read()
        except Exception as e:
            self._render_error(f"读取Markdown文件失败: {e}")
            return
        
        # 渲染Markdown
        title = page_data.get('title', '')
        if title:
            title_label = ttk.Label(
                self.parent,
                text=title,
                font=('Arial', 18, 'bold')
            )
            title_label.pack(pady=10)
            self.current_widgets.append(title_label)
        
        try:
            md_frame = self.markdown_renderer.render_markdown(
                self.parent, 
                markdown_content,
                assets_root
            )
            self.current_widgets.append(md_frame)
        except Exception as e:
            self._render_error(f"渲染Markdown失败: {e}")
    
    def _render_markdown_error_page(self, page_data):
        """渲染Markdown错误页面"""
        error_frame = ttk.Frame(self.parent)
        error_frame.pack(fill=tk.BOTH, expand=True)
        self.current_widgets.append(error_frame)
        
        error_label = ttk.Label(
            error_frame,
            text="Markdown支持未启用\n请安装依赖: pip install tkinterweb markdown2",
            foreground='red',
            font=('Arial', 12),
            justify=tk.CENTER
        )
        error_label.pack(expand=True)
    
    def _render_unknown_page(self, page_data, mcui_data):
        """渲染未知页面类型"""
        error_frame = ttk.Frame(self.parent)
        error_frame.pack(fill=tk.BOTH, expand=True)
        self.current_widgets.append(error_frame)
        
        error_label = ttk.Label(
            error_frame,
            text=f"未知页面类型: {page_data.get('type', '未指定')}",
            foreground='red',
            font=('Arial', 12)
        )
        error_label.pack(expand=True)
    
    def _render_error(self, message):
        """渲染错误消息"""
        error_frame = ttk.Frame(self.parent)
        error_frame.pack(fill=tk.BOTH, expand=True)
        self.current_widgets.append(error_frame)
        
        error_label = ttk.Label(
            error_frame,
            text=message,
            foreground='red',
            font=('Arial', 12)
        )
        error_label.pack(expand=True)